package com.conduit.commands.prototype;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conduit.WinReg.WindowsReqistry;
import com.conduit.enums.ResultCode;

public abstract class AbstractGetValueCommand extends AbstractCommand {

	@Override
	public void executeWithArgs(String args) {
		// validate command syntax
		if (!args.matches(commandSyntax)) {
			setResult("Error in Command's syntax (\"" + args + "\")");
			setResultCode(ResultCode.Error);
			return;
		}
		// get commnad's arguments
		Matcher matcher = Pattern.compile(commandSyntax).matcher(args);
		if (matcher.find()) {
			String textInput = matcher.group(1).trim();
			String regex = matcher.group(2).trim();
			String saveAsArgument = matcher.group(3).trim();
			// get expected value from command
			// get actual result
			try {
				String fileContent = getFileContent(textInput);
				Matcher resultMatcher = Pattern.compile(regex).matcher(
						fileContent);
				if (resultMatcher.find()) {
					setResult(saveAsArgument + " is a " + resultMatcher.group(1));
					setReturnValue(true);
					setResultCode(ResultCode.Successes);
				} else {
					setResult("Could not find regex " + regex+" in "+textInput);
					setReturnValue(false);
					setResultCode(ResultCode.Error);
				}
			} catch (Exception e) {
				setResult(e.getMessage());
				setResultCode(ResultCode.Error);
			}
		}

	}

	protected abstract String getFileContent(String textInput) throws Exception;

}
